﻿/*
  Version: MPL 1.1/GPL 2.0/LGPL 2.1
 
  The contents of this file are subject to the Mozilla Public License Version
  1.1 (the "License"); you may not use this file except in compliance with
  the License. You may obtain a copy of the License at
  http://www.mozilla.org/MPL/
  
  Software distributed under the License is distributed on an "AS IS" basis,
  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  for the specific language governing rights and limitations under the
  License.
  
  The Original Code is [maashaack framework].
  
  The Initial Developers of the Original Code are
  Zwetan Kjukov <zwetan@gmail.com> and Marc Alcaraz <ekameleon@gmail.com>.
  Portions created by the Initial Developers are Copyright (C) 2006-2014
  the Initial Developers. All Rights Reserved.
  
  Contributor(s):
  
  Alternatively, the contents of this file may be used under the terms of
  either the GNU General Public License Version 2 or later (the "GPL"), or
  the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
  in which case the provisions of the GPL or the LGPL are applicable instead
  of those above. If you wish to allow use of your version of this file only
  under the terms of either the GPL or the LGPL, and not to allow others to
  use your version of this file under the terms of the MPL, indicate your
  decision by deleting the provisions above and replace them with the notice
  and other provisions required by the LGPL or the GPL. If you do not delete
  the provisions above, a recipient may use your version of this file under
  the terms of any one of the MPL, the GPL or the LGPL.
 */
package molecule.render.starling.display
{
    import core.maths.replaceNaN;

    import graphics.Direction;
    import graphics.geom.EdgeMetrics;

    import molecule.render.starling.textures.HScale3Texture;
    import molecule.render.starling.textures.VScale3Texture;

    import starling.core.RenderSupport;
    import starling.display.DisplayObject;
    import starling.display.Image;
    import starling.display.QuadBatch;
    import starling.display.Sprite;
    import starling.events.Event;
    import starling.textures.Texture;
    import starling.textures.TextureSmoothing;
    import starling.utils.MatrixUtil;

    import flash.errors.IllegalOperationError;
    import flash.geom.Matrix;
    import flash.geom.Point;
    import flash.geom.Rectangle;
    
    /**
     * Scales an image like a "pill" shape with three regions, either horizontally or vertically. 
     * The edge regions scale while maintaining aspect ratio, and the middle region stretches to fill the remaining space.
     */
    public class Scale3Sprite extends Sprite
    {
        /**
         * Creates a new Scale3Sprite instance.
         * @param texture The texture displayed by this sprite.
         * @param direction The direction of the scale "horizontal" or "vertical"
         * @param textureScale The amount to scale the texture. Useful for DPI changes.
         */
        public function Scale3Sprite( texture:Texture , margin:EdgeMetrics = null , direction:String = "horizontal" , textureScale:Number = 1 )
        {
            _hitArea = new Rectangle() ;
            _batch   = new QuadBatch();
            
            _batch.touchable = false;
            
            addChild(_batch) ;
            
            addEventListener( Event.FLATTEN, _flatten ) ;
            
            _direction    = direction == Direction.HORIZONTAL ? Direction.HORIZONTAL : Direction.VERTICAL ;
            
            if( margin )
            {
                _margin.left   = replaceNaN( margin.left   ) ;
                _margin.top    = replaceNaN( margin.top    ) ;
                _margin.right  = replaceNaN( margin.right  ) ;
                _margin.bottom = replaceNaN( margin.bottom ) ;
            }
            
            _textureScale = textureScale ;
            
            this.texture = texture ;
        }
        
        /**
         * The color value to pass to the images.
         */
        public function get color():uint
        {
            return _color;
        }
        
        /**
         * @private
         */
        public function set color( value:uint ):void
        {
            if ( _color == value )
            {
                return;
            }
            _color = value;
            _changed = true;
        }
        
        /**
         * The direction of the sub-texture layout.
         * @see graphics.Direction#HORIZONTAL
         * @see graphics.Direction#VERTICAL
         */
        public function get direction():String
        {
            return _direction;
        }
        
        /**
         * @private
         */
        public function set direction( value:String ):void
        {
            _direction = value == Direction.HORIZONTAL ? Direction.HORIZONTAL : Direction.VERTICAL ;
            updateTexture() ;
        }
        
        /**
         * @private
         */
        public override function get height():Number
        {
            return _height;
        }
        
        /**
         * @private
         */
        public override function set height(value:Number):void
        {
            if ( _height == value )
            {
                return;
            }
            _height = _hitArea.height = value;
            _changed = true;
        }
        
        /**
         * The texture for the first region.
         */
        public function get margin():EdgeMetrics
        {
            return _margin;
        }
        
        /**
         * The size of the first region, in pixels.
         */
        public function set margin( em:EdgeMetrics ):void
        {
            _margin.left   = replaceNaN( em.left   ) ;
            _margin.top    = replaceNaN( em.top    ) ;
            _margin.right  = replaceNaN( em.right  ) ;
            _margin.bottom = replaceNaN( em.bottom ) ;
            updateTexture() ;
        }
        
        /**
         * The smoothing value to pass to the images.
         * @see starling.textures.TextureSmoothing
         */
        public function get smoothing():String
        {
            return _smoothing;
        }
        
        /**
         * @private
         */
        public function set smoothing( value:String ):void
        {
            if ( _smoothing == value )
            {
                return;
            }
            _smoothing = value;
            _changed = true;
        }
        
        /**
         * The texture displayed by this sprite.
         */
        public function get texture():Texture
        {
            return _texture;
        }
        
        /**
         * @private
         */
        public function set texture( value:Texture ):void
        {
            if ( !value )
            {
                throw new IllegalOperationError(this + " texture property failed, the Texture value cannot be null.") ;
            }
            
            if ( _texture == value )
            {
                return;
            }
            
            _texture = value ;
            
            updateTexture() ;
        }
        
        /**
         * The amount to scale the texture. Useful for DPI changes.
         */
        public function get textureScale():Number
        {
            return _textureScale;
        }
        
        /**
         * @private
         */
        public function set textureScale(value:Number):void
        {
            if ( _textureScale == value )
            {
                return;
            }
            _textureScale = value;
            _changed = true;
        }
        
        /**
         * @private
         */
        public override function get width():Number
        {
            return _width;
        }
        
        /**
         * @private
         */
        public override function set width(value:Number):void
        {
            if ( _width == value )
            {
                return;
            }
            _width = _hitArea.width = value;
            _changed = true;
        }
        
        /**
         * @private
         */
        public override function getBounds(targetSpace:DisplayObject, resultRect:Rectangle = null):Rectangle
        {
            if (!resultRect)
            {
                resultRect = new Rectangle();
            }
            
            var minX:Number = Number.MAX_VALUE, maxX:Number = -Number.MAX_VALUE;
            var minY:Number = Number.MAX_VALUE, maxY:Number = -Number.MAX_VALUE;
            
            if (targetSpace == this)
            {
                minX = _hitArea.x;
                minY = _hitArea.y;
                maxX = _hitArea.x + _hitArea.width;
                maxY = _hitArea.y + _hitArea.height;
            }
            else
            {
                getTransformationMatrix(targetSpace, _MATRIX);
                
                MatrixUtil.transformCoords(_MATRIX, _hitArea.x, _hitArea.y, _ORIGIN);
                minX = minX < _ORIGIN.x ? minX : _ORIGIN.x;
                maxX = maxX > _ORIGIN.x ? maxX : _ORIGIN.x;
                minY = minY < _ORIGIN.y ? minY : _ORIGIN.y;
                maxY = maxY > _ORIGIN.y ? maxY : _ORIGIN.y;
                
                MatrixUtil.transformCoords(_MATRIX, _hitArea.x, _hitArea.y + _hitArea.height, _ORIGIN);
                minX = minX < _ORIGIN.x ? minX : _ORIGIN.x;
                maxX = maxX > _ORIGIN.x ? maxX : _ORIGIN.x;
                minY = minY < _ORIGIN.y ? minY : _ORIGIN.y;
                maxY = maxY > _ORIGIN.y ? maxY : _ORIGIN.y;
                
                MatrixUtil.transformCoords(_MATRIX, _hitArea.x + _hitArea.width, _hitArea.y, _ORIGIN);
                minX = minX < _ORIGIN.x ? minX : _ORIGIN.x;
                maxX = maxX > _ORIGIN.x ? maxX : _ORIGIN.x;
                minY = minY < _ORIGIN.y ? minY : _ORIGIN.y;
                maxY = maxY > _ORIGIN.y ? maxY : _ORIGIN.y;
                
                MatrixUtil.transformCoords(_MATRIX, _hitArea.x + _hitArea.width, _hitArea.y + _hitArea.height, _ORIGIN);
                minX = minX < _ORIGIN.x ? minX : _ORIGIN.x;
                maxX = maxX > _ORIGIN.x ? maxX : _ORIGIN.x;
                minY = minY < _ORIGIN.y ? minY : _ORIGIN.y;
                maxY = maxY > _ORIGIN.y ? maxY : _ORIGIN.y;
            }
            
            resultRect.x = minX;
            resultRect.y = minY;
            resultRect.width = maxX - minX;
            resultRect.height = maxY - minY;
            
            return resultRect;
        }
        
        /**
         * @private
         */
        public override function hitTest( localPoint:Point, forTouch:Boolean = false ):DisplayObject
        {
            if (forTouch && (!visible || !touchable))
            {
                return null;
            }
            return _hitArea.containsPoint(localPoint) ? this : null;
        }
        
        /**
         * @private
         */
        public override function flatten():void
        {
            _update();
            super.flatten() ;
        }
        
        /**
         * @private
         */
        public override function render( support:RenderSupport, parentAlpha:Number ):void
        {
            _update();
            super.render(support, parentAlpha);
        }
        
        /**
         * Readjusts the dimensions of the image according to its current
         * textures. Call this method to synchronize image and texture size
         * after assigning textures with a different size.
         */
        public function readjustSize():void
        {
            if( _frame )
            {
                width  = _frame.width  * _textureScale ;
                height = _frame.height * _textureScale ;
            }
        }
        
        /**
         * @private
         */
        private var _batch:QuadBatch;
        
        /**
         * @private
         */
        private var _changed:Boolean = true;
        
        /**
         * @private
         */
        private var _color:uint = 0xFFFFFF;
        
        /**
         * @private
         */
        private var _direction:String ;
        
        /**
         * @private
         */
        private var _frame:Rectangle;
        
        /**
         * @private
         */
        private var _hitArea:Rectangle;
        
        /**
         * @private
         */
        private static var _image:Image;
        
        /**
         * @private
         */
        private var _margin:EdgeMetrics = new EdgeMetrics() ;
        
        /**
         * @private
         */
        private static const _MATRIX:Matrix = new Matrix();
        
        /**
         * @private
         */
        private static const _ORIGIN:Point = new Point();
        
        /**
         * @private
         */
        private var _s3ht:HScale3Texture ;
        /**
         * @private
         */
        private var _s3vt:VScale3Texture ;
        
        /**
         * @private
         */
        private var _smoothing:String = TextureSmoothing.BILINEAR;
        
        /**
         * @private
         */
        private var _texture:Texture;
        
        /**
         * @private
         */
        private var _textureScale:Number = 1;
        
        /**
         * @private
         */
        private var _height:Number = NaN;
        
        /**
         * @private
         */
        private var _width:Number = NaN;
        
        /**
         * @private
         */
        private function _flatten( event:Event ):void
        {
            _update();
        }
        
        /**
         * @private
         */
        protected function _update():void
        {
            if ( _changed )
            {
                _batch.reset();
                if( _direction == Direction.HORIZONTAL )
                {
                    _updateH() ;
                }
                else
                {
                    _updateV() ;
                }
                _changed = false;
            }
        }
        
        /**
         * @private
         */
        private function updateTexture():void
        {
            _image = null ;
            _frame = _texture ? _texture.frame : null;
            _s3ht  = (_texture && _direction == Direction.HORIZONTAL) ? new HScale3Texture(_texture, _margin) : null ;
            _s3vt  = (_texture && _direction == Direction.VERTICAL) ? new VScale3Texture(_texture, _margin) : null ;
            if( _s3ht )
            {
                _image = new Image( _s3ht.left ) ;
            }
            else if ( _s3vt )
            {
                _image = new Image( _s3vt.top ) ;
            }
            readjustSize() ;
            _changed = true ;
        }
        
        /**
         * @private
         */
        protected function _updateH():void
        {
            if( _s3ht )
            {
                var margin:EdgeMetrics = _s3ht.margin ;
                
                var oppositeEdgeScale:Number = _height / _frame.height;
                
                _image.smoothing = _smoothing ;
                _image.color     = _color ;
                
                var first:Number  = margin.left * oppositeEdgeScale;
                var third:Number  = (_frame.width - margin.left - margin.right) * oppositeEdgeScale;
                var second:Number = _width - first - third;
                
                if ( _height > 0 )
                {
                    _image.texture = _s3ht.left;
                    _image.x      = 0;
                    _image.y      = 0;
                    _image.width  = first;
                    _image.height = _height;
                    
                    if (first > 0)
                    {
                        _batch.addImage(_image);
                    }
                    
                    _image.texture = _s3ht.center;
                    _image.x       = margin.left;
                    _image.y       = 0;
                    _image.width   = second ; 
                    _image.height  = _height;
                    
                    if (second > 0)
                    {
                        _batch.addImage(_image);
                    }
                    
                    _image.texture = _s3ht.right;
                    _image.x       = first + second ;
                    _image.y       = 0;
                    _image.width   = third ;
                    _image.height  = _height;
                    
                    if (third > 0)
                    {
                        _batch.addImage(_image);
                    }
                }
            }
        }
        
        /**
         * @private
         */
        protected function _updateV():void
        {
            if( _s3vt )
            {
                var oppositeEdgeScale:Number = _width / _frame.width;
                
                _image.smoothing = _smoothing ;
                _image.color     = _color ;
                
                var first:Number  = margin.top * oppositeEdgeScale;
                var third:Number  = (_frame.height - _margin.top - _margin.bottom) * oppositeEdgeScale;
                var second:Number = _height - first - third;
                
                if ( _width > 0 )
                {
                    _image.texture = _s3vt.top;
                    _image.x      = 0;
                    _image.y      = 0;
                    _image.width  = _width;
                    _image.height = first;
                    
                    if (first > 0)
                    {
                        _batch.addImage(_image);
                    }
                    
                    _image.texture = _s3vt.middle;
                    _image.x       = 0;
                    _image.y       = margin.top;
                    _image.width   = _width ; 
                    _image.height  = second;
                    
                    if (second > 0)
                    {
                        _batch.addImage(_image);
                    }
                    
                    _image.texture = _s3vt.bottom;
                    _image.x       = 0 ;
                    _image.y       = first + second;
                    _image.width   = _width ;
                    _image.height  = third;
                    
                    if (third > 0)
                    {
                        _batch.addImage(_image);
                    }
                }
            }
        }
    }
}
